package cn.zhj.controller;

import cn.zhj.utils.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    //获取yml的属性
    @Value("${file.path}")
    private String filePath;

    //MultipartFile photo - 接收文件。保证photo与前端的name属性值一致
    @PostMapping("/upload")
    public R<Void> uploadFile(MultipartFile photo) throws IOException {
        //获取原始文件名
        String oName = photo.getOriginalFilename(); //g5.jpg
        //获取文件的后缀
        String suffix = oName.substring(oName.lastIndexOf(".")); //.jpg
        //随机的名称：1.uuid 2.时间戳
        //String newName = System.currentTimeMillis()+suffix;
        String newName = UUID.randomUUID().toString()+suffix;

        //file可以自动创建目录
        File file = new File(filePath);
        //目录不存在 - 才创建
        if(!file.exists()){
            file.mkdirs();
        }
        //获取输入流
        InputStream in = photo.getInputStream();
        //输出流
        FileOutputStream out = new FileOutputStream(new File(file,newName));
        //实现拷贝
        IOUtils.copy(in,out);
        out.close();
        in.close();
        return R.ok();
    }

    @GetMapping("/download")
    //String fileName接收文件名-与前端一致。HttpServletResponse response-输出流
    public R downloadFile(String fileName, HttpServletResponse response) throws Exception {
        //告诉浏览器，文件不要直接显示出来。而是以下载的方式显示：下载的时候那个名字
        //中文名
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //通过路径和名字获取输入流
        FileInputStream in = new FileInputStream(new File(filePath, fileName));
        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(in,out);
        out.close();
        in.close();
        return R.ok();
    }
    
}
